from typing import Optional
from contextlib import redirect_stdout
from io import StringIO
from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
from fastapi.middleware.cors import CORSMiddleware

app = FastAPI()

class Func(BaseModel):
    code: str
    name: Optional[str] = None


@app.post("/coderun/")
async def code_run(func: Func):
    # exec code ,need to add filter to avoid unsecurity command
    # limit globals and locals variables

    f = StringIO()
    with redirect_stdout(f):
        exec(func.code)

    # return exec result
    return f.getvalue()
